<template>
  <div
    ref="chartsRef"
    v-loading="loading"
    style="width: 100%; height: 230px"
  ></div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'
import useFetch from '@/hooks/useFetch'
import { queryMatterAppraiseStatistics } from '@/api/home'
import { useRouter } from 'vue-router'
import { ELevelCounts } from '@/type/levelCounts'

const router = useRouter()

const { loading, execute, onFetchSuccess } = useFetch(
  queryMatterAppraiseStatistics,
)

const defaultData = [
  {
    value: 0,
    name: '优',
    key: ELevelCounts['优'],
    itemStyle: {
      color: '#0052D9',
    },
  },
  {
    value: 0,
    name: '良',
    key: ELevelCounts['良'],
    itemStyle: {
      color: '#2BA471',
    },
  },
  {
    value: 0,
    name: '中',
    key: ELevelCounts['中'],
    itemStyle: {
      color: '#E37318',
    },
  },
  {
    value: 0,
    name: '差',
    key: ELevelCounts['差'],
    itemStyle: {
      color: '#D54941',
    },
  },
]

const chartsData = ref(defaultData)

onFetchSuccess((data) => {
  const newData = defaultData.map((item) => ({
    ...item,
    value: data[item.key],
  }))
  chartsData.value = newData
  initCharts()
})

const chartsRef = ref<HTMLDivElement>(null)

const defaultOptions = {
  legend: {
    top: 'bottom',
    icon: 'circle',
  },
  toolbox: {},
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c} ({d}%)',
  },
  series: [
    {
      name: '决策落实办理统计',
      type: 'pie',
      radius: [10, 90],
      center: ['50%', '50%'],
      roseType: 'area',
      itemStyle: {
        borderRadius: 8,
      },
      data: [],
    },
  ],
}

const options = computed(() => ({
  ...defaultOptions,
  grid: {
    left: '10%',
    right: 0,
    bottom: 0,
  },
  series: [
    {
      ...defaultOptions.series[0],
      data: chartsData.value,
    },
  ],
}))

const charts = ref(null)

onMounted(() => {
  init()
})

const init = async () => {
  await execute()
}

const initCharts = () => {
  if (chartsRef?.value) {
    const chart = echarts.init(chartsRef.value)
    chart.setOption(options.value)
    charts.value = chart
    chart.on('click', (params) => {
      router.push({
        path: '/mission/follow',
        query: {
          level: ELevelCounts[params.name],
        },
      })
    })
    // 窗口变化自适应
    window.addEventListener('resize', handleResize)
  }
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  charts.value?.resize()
}
</script>
